using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace DocumentCreationSystem
{
    /// <summary>
    /// 数据清理功能测试程序
    /// </summary>
    public class TestDataCleanup
    {
        private readonly IDataStorageService _dataStorage;
        private readonly DataCleanupService _cleanupService;
        private readonly ILogger<TestDataCleanup> _logger;

        public TestDataCleanup(IServiceProvider serviceProvider)
        {
            _dataStorage = serviceProvider.GetRequiredService<IDataStorageService>();
            var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
            _cleanupService = new DataCleanupService(_dataStorage, loggerFactory.CreateLogger<DataCleanupService>());
            _logger = loggerFactory.CreateLogger<TestDataCleanup>();
        }

        /// <summary>
        /// 运行数据清理测试
        /// </summary>
        public async Task RunTestAsync()
        {
            try
            {
                _logger.LogInformation("=== 开始数据清理功能测试 ===");

                // 1. 加载现有数据
                await _dataStorage.LoadAsync();
                _logger.LogInformation("数据加载完成");

                // 2. 检查数据完整性
                _logger.LogInformation("检查数据完整性...");
                var integrityReport = await _cleanupService.GetDataIntegrityReportAsync();
                
                _logger.LogInformation($"数据完整性检查结果:");
                _logger.LogInformation($"  是否有效: {integrityReport.IsValid}");
                _logger.LogInformation($"  总问题数: {integrityReport.TotalIssuesCount}");
                
                if (!string.IsNullOrEmpty(integrityReport.ErrorMessage))
                {
                    _logger.LogError($"  错误信息: {integrityReport.ErrorMessage}");
                }

                if (integrityReport.HasAnyIssues)
                {
                    _logger.LogWarning("发现数据完整性问题:");
                    
                    if (integrityReport.OrphanedDocuments.Count > 0)
                        _logger.LogWarning($"  孤立文档: {integrityReport.OrphanedDocuments.Count} 个");
                    
                    if (integrityReport.OrphanedNovelProjects.Count > 0)
                        _logger.LogWarning($"  孤立小说项目: {integrityReport.OrphanedNovelProjects.Count} 个");
                    
                    if (integrityReport.OrphanedChapters.Count > 0)
                        _logger.LogWarning($"  孤立章节: {integrityReport.OrphanedChapters.Count} 个");
                    
                    if (integrityReport.OrphanedCharacters.Count > 0)
                        _logger.LogWarning($"  孤立角色: {integrityReport.OrphanedCharacters.Count} 个");
                    
                    if (integrityReport.OrphanedVectorRecords.Count > 0)
                        _logger.LogWarning($"  孤立向量记录: {integrityReport.OrphanedVectorRecords.Count} 个");
                    
                    if (integrityReport.OrphanedWorldSettings.Count > 0)
                        _logger.LogWarning($"  孤立世界设定: {integrityReport.OrphanedWorldSettings.Count} 个");
                    
                    if (integrityReport.DuplicateProjectIds.Count > 0)
                        _logger.LogWarning($"  重复项目ID: {string.Join(", ", integrityReport.DuplicateProjectIds)}");
                    
                    if (integrityReport.DuplicateDocumentIds.Count > 0)
                        _logger.LogWarning($"  重复文档ID: {string.Join(", ", integrityReport.DuplicateDocumentIds)}");
                    
                    if (integrityReport.DuplicateNovelProjectIds.Count > 0)
                        _logger.LogWarning($"  重复小说项目ID: {string.Join(", ", integrityReport.DuplicateNovelProjectIds)}");
                }
                else
                {
                    _logger.LogInformation("✅ 数据完整性检查通过，未发现问题");
                }

                // 3. 创建备份
                _logger.LogInformation("创建数据备份...");
                var backup = await _cleanupService.CreateBackupAsync("测试前备份");
                
                if (backup != null)
                {
                    _logger.LogInformation($"✅ 备份创建成功: {backup.BackupPath}");
                    _logger.LogInformation($"   备份大小: {backup.BackupSize / 1024.0:F1} KB");
                }
                else
                {
                    _logger.LogWarning("❌ 备份创建失败");
                }

                // 4. 执行数据清理（如果有问题需要清理）
                if (integrityReport.HasAnyIssues)
                {
                    _logger.LogInformation("执行数据清理...");
                    
                    var cleanupOptions = new DataCleanupOptions
                    {
                        CleanOrphanedDocuments = true,
                        CleanOrphanedNovelProjects = true,
                        CleanOrphanedChapters = true,
                        CleanOrphanedCharacters = true,
                        CleanOrphanedVectorRecords = true,
                        CleanOrphanedWorldSettings = true,
                        CreateBackup = false // 已经创建过备份了
                    };

                    var cleanupResult = await _cleanupService.PerformFullCleanupAsync(cleanupOptions);
                    
                    _logger.LogInformation($"数据清理结果:");
                    _logger.LogInformation($"  是否成功: {cleanupResult.IsSuccess}");
                    _logger.LogInformation($"  消息: {cleanupResult.Message}");
                    
                    if (cleanupResult.IsSuccess && cleanupResult.HasAnyCleanup)
                    {
                        _logger.LogInformation("清理详情:");
                        
                        if (cleanupResult.RemovedDocumentsCount > 0)
                            _logger.LogInformation($"  清理文档: {cleanupResult.RemovedDocumentsCount} 个");
                        
                        if (cleanupResult.RemovedNovelProjectsCount > 0)
                            _logger.LogInformation($"  清理小说项目: {cleanupResult.RemovedNovelProjectsCount} 个");
                        
                        if (cleanupResult.RemovedChaptersCount > 0)
                            _logger.LogInformation($"  清理章节: {cleanupResult.RemovedChaptersCount} 个");
                        
                        if (cleanupResult.RemovedCharactersCount > 0)
                            _logger.LogInformation($"  清理角色: {cleanupResult.RemovedCharactersCount} 个");
                        
                        if (cleanupResult.RemovedVectorRecordsCount > 0)
                            _logger.LogInformation($"  清理向量记录: {cleanupResult.RemovedVectorRecordsCount} 个");
                        
                        if (cleanupResult.RemovedWorldSettingsCount > 0)
                            _logger.LogInformation($"  清理世界设定: {cleanupResult.RemovedWorldSettingsCount} 个");
                        
                        _logger.LogInformation($"  总清理数量: {cleanupResult.TotalRemovedCount} 个");
                    }
                    else if (cleanupResult.IsSuccess && !cleanupResult.HasAnyCleanup)
                    {
                        _logger.LogInformation("✅ 未发现需要清理的数据");
                    }
                }
                else
                {
                    _logger.LogInformation("数据完整性良好，跳过清理步骤");
                }

                // 5. 再次检查数据完整性
                _logger.LogInformation("再次检查数据完整性...");
                var finalReport = await _cleanupService.GetDataIntegrityReportAsync();
                
                if (finalReport.IsValid && !finalReport.HasAnyIssues)
                {
                    _logger.LogInformation("✅ 最终数据完整性检查通过");
                }
                else
                {
                    _logger.LogWarning($"⚠️ 仍有 {finalReport.TotalIssuesCount} 个问题需要处理");
                }

                // 6. 查看备份列表
                _logger.LogInformation("查看备份列表...");
                var backups = await _cleanupService.GetBackupListAsync();
                _logger.LogInformation($"当前备份数量: {backups.Count}");
                
                foreach (var backupInfo in backups.Take(5)) // 只显示最近5个
                {
                    _logger.LogInformation($"  {backupInfo.CreatedAt:yyyy-MM-dd HH:mm:ss} - {backupInfo.BackupSize / 1024.0:F1} KB");
                }

                _logger.LogInformation("=== 数据清理功能测试完成 ===");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据清理测试失败");
                throw;
            }
        }

        /// <summary>
        /// 创建测试数据（用于测试清理功能）
        /// </summary>
        public async Task CreateTestDataAsync()
        {
            try
            {
                _logger.LogInformation("创建测试数据...");

                // 注意：这里只是示例，实际使用时要小心
                // 可以创建一些测试用的无效引用数据来验证清理功能
                
                _logger.LogInformation("测试数据创建完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建测试数据失败");
                throw;
            }
        }
    }
}
